<!--  -->
<template>
  <div>
    <a-modal
      :title="targetManagement.target || '--'"
      :width="680"
      :visible="visible"
      :confirmLoading="loading"
      :footer="getFooter"
      @ok="
        () => {
          $emit('ok');
        }
      "
      @cancel="
        () => {
          $emit('cancel');
        }
      "
    >
      <a-spin :spinning="loading">
        <div class="tips" >
          <div style="white-space:nowrap">评分依据：</div>
          <div style="white-space: pre-wrap;">{{ targetManagement.comment || "暂无" }}</div>
        </div>
        <div class="datum">
          备查资料：{{ targetManagement.backUpData || "暂无" }}
        </div>
        <div style="margin-top: 15px; display: flex">
          <span>参考文件</span>
          <div>
            <div v-for="(file, index) in targetManagement.files" :key="index">
              <img
                class="word"
                src="@/assets/word.png"
                alt=""
                v-if="file.type === 'doc' || file.type === 'docx'"
              />
              <img class="pdf" src="@/assets/pdf.png" alt="" v-else />
              <span class="required" @click="handlePreview(file)">{{
                file.original || ""
              }}</span>
            </div>
          </div>
        </div>
        <div style="margin-top: 12px">
          <input
            ref="uploadFile"
            type="file"
            multiple
            style="display: none"
            class="file-input"
            @change="change"
            accept="image/*,.pdf,.doc,.docx"
          />
          <span
            >填报文件<img class="file" src="@/assets/tips.png" alt=""
          /></span>
          <a-button
            type="primary"
            @click="handleUpload"
            :disabled="status !== 2 ? true : false"
            >点击上传</a-button
          >
          <span @click="handleSelect" class="select_file">选择文件</span>
          <div class="remark">
            注：选择已上传的文件，避免重复操作，只能上传pdf，word，图片文件，且不超过100M
          </div>
          <div style="margin-left: 85px">
            <div>
              <div
                style="
                  display: flex;
                  align-items: center;
                  cursor: pointer;
                  margin-top: 5px;
                  margin-bottom: 5px;
                "
                v-for="(item, index) in files"
                :key="index"
                @click="handlePreview(item)"
              >
                <div
                  style="
                    margin-right: 10px;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    white-space: nowrap;
                    width: 200px;
                  "
                >
                  {{ item.original }}
                </div>
                <a-icon type="close" @click.stop="deleteFile(index)" />
              </div>
            </div>
          </div>
        </div>
        <div class="file_list" v-show="fileList.length">
          <span>合并后文件</span>
          <div
            class="file_container"
            v-for="(item, index) in fileList"
            :key="index"
          >
            <img
              class="word"
              src="@/assets/word.png"
              alt=""
              v-if="item.type === 'docx' || item.type === 'doc'"
            />
            <span class="required" @click="handleLook(item)">{{
              item.original
            }}</span>
            <img
              class="delete"
              src="@/assets/delete.png"
              alt=""
              @click="handleDelete(item, index)"
            />
            <a-button @click="handleLook(item)" style="margin-left: 15px;" type="primary">预览</a-button>
          </div>
        </div>
        <div class="form_item">
          <span>自评得分</span>
          <a-input-number
            :min="0"
            :max="Number(targetManagement.totalPoint)"
            style="width: 353px; margin-left: 16px; height: 36px;margin-right: 16px; "
            :disabled="status !== 2 ? true : false"
            v-model="queryParam.selfScore"
            placeholder=" "
          />
          <span>总分：{{targetManagement.totalPoint}}</span>
        </div>
        <div class="form_item second">
          <span>备注说明</span>
          <a-input
            v-model="queryParam.comment"
            :disabled="status !== 2 ? true : false"
            placeholder=" "
            type="textarea"
          />
        </div>

        <!-- 指导意见 -->
        <div v-if="replyList.length">
          <div class="instruction">
            <div class="title">指导意见</div>
            <div class="collapse" >
              <!-- <span>{{ targetManagement.target }}</span> -->
              <div @click="handleExpend">
                <span style="color: #4477f8; margin-right: 5px">{{
                  expend ? "展开" : "收起"
                }}</span>
                <a-icon type="down" style="color: #4477f8" v-if="expend" />
                <a-icon type="up" style="color: #4477f8" v-else />
              </div>
            </div>
          </div>
          <div v-if="showInstruction">
            <div class="time_line">
              <div
                class="tine_line_item"
                v-for="(item, index) in replyList"
                :key="index"
              >
                <div class="tine_line_item_left">
                  <div></div>
                  <div class="line"></div>
                </div>
                <div class="tine_line_item_right">
                  <div
                    :style="{
                      color: item.type === null ? '#4D70F8' : '#FEA538',
                    }"
                  >
                    {{ item.type == null ? "社会组织" : "指导专家" }}
                    {{ item.createTime }}
                  </div>
                  <div>{{ item.content }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="scoreList.length">
          <div class="instruction">
            <div class="title">专家意见</div>
            <div class="collapse" >
              <!-- <span>{{ targetManagement.target }}</span> -->
              <div @click="handleExpertExpend">
                <span style="color: #4477f8; margin-right: 5px">{{
                  expertExpend ? "展开" : "收起"
                }}</span>
                <a-icon type="down" style="color: #4477f8" v-if="expertExpend" />
                <a-icon type="up" style="color: #4477f8" v-else />
              </div>
            </div>
          </div>
          <div v-if="showExpertOpinion">
            <div class="time_line">
              <div
                class="tine_line_item"
                v-for="(item, index) in scoreList"
                :key="index"
              >
                <div class="tine_line_item_left">
                  <div></div>
                  <div class="line"></div>
                </div>
                <div class="tine_line_item_right">
                  <div
                    :style="{
                      color: item.type === null ? '#4D70F8' : '#FEA538',
                    }"
                  >
                    {{ item.createTime }}
                  </div>
                  <div>{{ item.annotation || '--' }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </a-spin>
    </a-modal>
    <a-modal
      title="选择文件"
      :width="640"
      :visible="fileVisible"
      :confirmLoading="fileLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="fileLoading">
        <a-form :form="form" v-bind="formLayout" ref="form">
          <a-form-item label="文件">
            <a-select
              mode="multiple"
              placeholder="请选择文件"
              option-label-prop="label"
              :filterOption="filterOption"
              v-decorator="[
                'leader',
                { rules: [{ required: true, message: '请选择文件' }] },
              ]"
            >
              <a-select-option
                v-for="(file, index) in fileListBefore"
                :key="index"
                :value="file.id"
                :label="file.original"
                >{{ file.original }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
    <a-modal
      title="word预览"
      :width="1000"
      :visible="previewVisible"
      :footer="null"
      @cancel="
        () => {
          previewVisible = false;
        }
      "
    >
      <div class="docx_container">
        <div class="home">
          <div ref="file"></div>
        </div>
        <div v-if="previewLoading" class="spinBox">
          <a-spin></a-spin>
        </div>
      </div>
      
    </a-modal>
    <a-modal
      title="pdf预览"
      :width="1000"
      :visible="pdfPreviewVisible"
      :footer="null"
      @cancel="
        () => {
          pdfPreviewVisible = false;
          pdfUrl = '';
        }
      "
    >
        <div class="docx_container">
          <pdf v-for="i in numPages" :key="i" :page="i" :src="pdfUrl" ref="pdf"></pdf>
          <div v-if="previewLoading" class="spinBox">
            <a-spin></a-spin>
          </div>
        </div>
    </a-modal>
    <a-modal
      title="图片预览"
      :width="640"
      :visible="picPreviewVisible"
      :footer="null"
      @cancel="picPreviewCancel"
    >
      <img :src="picUrl" style="width: 100%;height:auto"></img>
    </a-modal>
  </div>
</template>

<script>
import axios from "axios";
const docx = require("docx-preview");
import pdf from "vue-pdf";
import storejs from "store";
import { baseApi, fileApi, ossUrl } from '@/config'
export default {
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    status: "",
  },
  components: { pdf },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 },
      },
    };
    return {
      previewLoading: false,
      form: this.$form.createForm(this),
      expend: true, // true 展开 false 收起
      showInstruction: false, // 指导意见
      expertExpend: true,
      showExpertOpinion: false, // 专家意见
      fileVisible: false, // 选择文件
      queryParam: {
        selfScore: "", // 自评得分
        comment: "", // 备注说明
      },
      files: [], // 提交给后台的文件列表
      fileList: [], // 合并后文件列表
      replyList: [], // 回复列表
      scoreList: [],
      fileLoading: false, // 上传文件时的loading
      previewVisible: false, // 预览word pic
      targetManagement: {}, // 说明 备查资料 参考资料
      pdfUrl: "",
      pdfPreviewVisible: false,
      fileListBefore: [], // 历史文件列表
      picPreviewVisible: false,
      picUrl: "",
      numPages: null,
    };
  },
  methods: {
    picPreviewCancel() {
      this.picUrl = ''
      this.picPreviewVisible = false
    },
    // 判断底部按钮
    getFooter() {
      if (this.status !== 2) {
        return null; // 没有按钮
      } else {
        return undefined;
      }
    },
    // 选择文件
    handleSelect() {
      if (this.status !== 2) return this.$message.info("该体系不在填报中！");
      this.fileVisible = true;
    },
    // 删除文件
    handleDelete(item, index) {
      this.fileList.splice(index, 1);
    },
    // 展开收起
    handleExpend() {
      this.expend = !this.expend;
      this.showInstruction = !this.showInstruction;
    },
    handleExpertExpend() {
      this.expertExpend = !this.expertExpend;
      this.showExpertOpinion = !this.showExpertOpinion;
    },
    // 取消
    handleCancel() {
      this.fileVisible = false;
      this.$refs.form.form.resetFields();
    },
    // 选择文件
    change(e) {
      this.$emit("update:loading", true);
      // console.log(e);
      let param = new FormData();
      for (let i = 0; i < e.target.files.length; i++) {
        if (e.target.files[i].size / 1024 / 1024 > 100) {
          this.$message.error(`${e.target.files[i].name}大于100M,请检查`);
          this.$emit("update:loading", false);
          return;
        } else {
          param.append("files", e.target.files[i]); //这里append中的file，是给文件，起的名字，后端通过该名字获取指定文件
        }
      }

      axios
        .post(
          baseApi + "/minio/uploadFiles",
          //"http://124.70.184.139/grade-evaluation-api/minio/uploadFiles",
          param,
          {
            headers: {
              Authorization: storejs.get("token"),
              "Content-type": "multipart/form-data",
            },
            "Content-type": "multipart/form-data",
          }
        )
        .then((res) => {
          // console.log(res);
          this.files.push(...res.data.data);
          this.$emit("update:loading", false);
          // if (res.data.code === 0) {
          // }
        })
        .catch((err) => {
          this.$emit("update:loading", false);
        });
    },
    // 上传文件
    handleUpload() {
      // console.log(this.$refs.uploadFile);
      this.$refs.uploadFile.click();
      this.$refs.uploadFile.value = "";
    },
    // 选择文件
    handleOk() {
      this.$refs.form.form.validateFields((errors, values) => {
        if (!errors) {
          this.fileLoading = true;
          // console.log("values", values);
          values.leader.forEach((item) => {
            this.fileListBefore.forEach((file) => {
              if (file.id === item) {
                this.files.push(file);
              }
            });
            this.fileLoading = false;
            this.fileVisible = false;
          });
        } else {
          this.fileLoading = false;
        }
      });
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    handlePreview(file) {
      this.previewLoading = true;
      const url = file.url.indexOf('pinggu.mkcom.cn') > -1 ? file.url : location.origin + '/grade-evaluation-file/' + file.url
      if (file.type === "doc" || file.type === "docx") {
        this.previewVisible = true;
        axios({
          method: "get",
          responseType: "blob", // 设置响应文件格式
          url: url,
        })
          .then(({ data }) => {
            docx.renderAsync(data, this.$refs.file); // 渲染到页面预览
          })
          .finally(() => {
            this.previewLoading = false;
          });
      } else if (file.type === "pdf") {
        this.pdfUrl = pdf.createLoadingTask({
          url: url,
          withCredentials: false,
        });
        this.pdfUrl.promise
          .then((pdf) => {
            this.numPages = pdf.numPages;
            console.log(this.numPages);
          })
          .catch((err) => {
            console.error("pdf 加载失败", err);
          })
          .finally(() => {
            this.previewLoading = false;
          });
        this.pdfPreviewVisible = true;
      } else {
        this.picUrl = url;
        this.picPreviewVisible = true;
      }
      // window.open(file.url, "_blank");
    },
    handleLook(data) {
      // 服务器本地访问
      let url = ossUrl + data.url
      if (!data.bucketName) {
        url = data.url.indexOf('pinggu.mkcom.cn') > -1 ? data.url : fileApi + data.url
      }
      axios({
        method: "get",
        responseType: "blob", // 设置响应文件格式
        url,
      })
        .then(({ data }) => {
          docx.renderAsync(data, this.$refs.file); // 渲染到页面预览
        })
        .catch(e => {
          this.$refs.file.innerHTML = '<div style="color: red;text-align: center; opacity: .8;">加载文件异常</div>'
        })
        .finally(() => {
          this.previewLoading = false;
        });
        this.previewLoading = true
        this.previewVisible = true
    },
    deleteFile(index) {
      this.files.splice(index, 1);
    },
  },
};
</script>
<style lang="less" scoped>
.tips {
  display: flex;
}
.tips,
.datum {
  background: #edf3ff;
  border-radius: 12px;
  padding: 24px 0 24px 21px;
}

.datum {
  background: #fff9eb;
  margin-top: 11px;
}

img {
  width: 25px;
  height: 25px;
}

.word {
  margin-left: 28px;
}

.required {
  color: blue;
  margin-left: 4px;
  cursor: pointer;
}

.pic {
  margin-left: 50px;
}

.pdf {
  margin-left: 28px;
  width: 25px;
  height: 25px;
}

.file {
  width: 14px;
  height: 14px;
  margin-left: 5px;
  margin-right: 12px;
}

.select_file {
  margin-left: 19px;
  color: #4d70f8;
  cursor: pointer;
}

.remark {
  color: #999;
  margin-top: 12px;
  margin-left: 85px;
  font-family: PingFang SC;
  font-weight: 500;
}

.file_list {
  display: flex;
  align-items: center;
  .file_container:nth-child(n + 2) {
    margin-top: 5px;
  }

  .file_container {
    display: flex;
    align-items: center;
    margin-left: 15px;
    .word {
      margin-left: 0;
    }

    .required {
      margin-left: 0;
      cursor: pointer;
    }

    .delete {
      width: 14px;
      height: 14px;
      margin-left: 22px;
      cursor: pointer;
    }
  }
}

.form_item {
  display: flex;
  align-items: center;
  margin-top: 20px;

  ::v-deep .ant-input {
    margin-left: 16px;
    height: 36px;
    width: 353px;
  }
}

.second {
  padding-bottom: 38px;
  border-bottom: 1px solid #f0f0f0;

  ::v-deep .ant-input {
    margin-left: 16px;
    height: 111px;
    width: 353px;
  }
}

.instruction {
  margin-top: 19px;

  .title {
    font-size: 16px;
  }

  .collapse {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    // margin-top: 26px;
    color: #666;

    div {
      cursor: pointer;

      img {
        margin-left: 12px;
      }
    }
  }
}

.time_line {
  margin: 13px 0 21px 35px;

  .tine_line_item {
    display: flex;
    padding-bottom: 20px;

    .tine_line_item_left {
      div:first-child {
        width: 12px;
        height: 12px;
        border: 2px solid #5984fb;
        border-radius: 50%;
      }

      .line {
        width: 1px;
        background: #5984fb;
        height: 100%;
        margin-top: 2px;
        margin-left: 6px;
      }
    }

    .tine_line_item_right {
      margin-left: 22px;
      color: #999;
      line-height: 14px;

      div:nth-child(n + 2) {
        margin-top: 10px;
      }

      div:first-child {
        color: #4d70f8;
      }

      div:nth-child(3) {
        color: #fea538;
      }
    }
  }
}

.reply {
  display: flex;
  align-items: center;
  margin-left: 33px;

  ::v-deep .ant-input {
    width: 394px;
    border-radius: 19px;
    height: 38px;
  }

  ::v-deep .ant-btn {
    margin-left: 11px;
    border-radius: 19px;
  }
}

.home {
  width: 100%;
}

::v-deep .docx-wrapper {
  padding: none;
  background: none;
}

::v-deep .docx {
  width: auto !important;
  padding: 0px !important;
  box-shadow: none !important;
}
::v-deep .ant-input-number-handler-wrap {
  display: none;
}
.docx_container {
  position: relative;
  min-height: 500px;
  .spinBox {
    display: flex;
    justify-content: center;
    background: #fff;
    width: 100%;
    height: 100%;
    padding-top: 150px;
  }
}
</style>
